/* 深拷贝数据对象 */
export function copyData(target) {
  if (typeof target === "object") {
    let cloneTarget = Array.isArray(target) ? [] : {};
    for (const key in target) {
      cloneTarget[key] = copyData(target[key]);
    }
    return cloneTarget;
  } else {
    return target;
  }
}

/**格式化金额保留小数点后两位 */
export function formatNumber(value, num) {
  num = num > 0 && num <= 20 ? num : 2;
  value = parseFloat((value + "").replace(/[^\d\.-]/g, "")).toFixed(num) + "";
  var valueArr = value.split(".")[0].split("");
  var valueFloat = value.split(".")[1];
  var valueString = "";
  for (let i = 0; i < valueArr.length; i++) {
    valueString += valueArr[i] + ((i + 1) % 3 == 0 && i + 1 != valueArr.length ? "," : "");
  }
  var money = valueString.split("").join("") + "." + valueFloat;

  return money;
}

/** 给手机号隐藏加* */
export function phoneNumberEncry(phone) {
  phone = String(phone);
  return `${phone.slice(0, 3)}****${phone.slice(7)}`;
}

/** 数组去重 */
export function unique(arr) {
  if (!Array.isArray(arr)) {
    console.log("type error!");
    return;
  }
  arr = arr.sort();
  var arrry = [arr[0]];
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] !== arr[i - 1]) {
      arrry.push(arr[i]);
    }
  }
  return arrry;
}

export function uniqueNoSort(arr) {
  if (!Array.isArray(arr)) {
    console.log("type error!");
    return;
  }
  var arrry = [arr[0]];
  for (var i = 1; i < arr.length; i++) {
    var isExist = false;
    for (var j = 0; j < arrry.length; j++) {
      if (arr[i] === arrry[j]) {
        isExist = true;
        break;
      }
    }
    if (!isExist) arrry.push(arr[i]);
  }
  return arrry;
}

/** 补全两位 */
function repairTwoStr(num) {
  return num < 10 ? "0" + num : "" + num;
}

/** 格式化秒为具体的时分秒 */
export function formatSeconds(value, isColon = false) {
  let result = parseInt(value);
  let h = Math.floor(result / 3600);
  let m = Math.floor((result / 60) % 60);
  let s = Math.floor(result % 60);

  if (isColon) {
    h = h ? repairTwoStr(h) : "00";
    m = m ? repairTwoStr(m) : "00";
    s = s ? repairTwoStr(s) : "00";

    return `${h}:${m}:${s}`;
  } else {
    h = h ? repairTwoStr(h) + "时" : "";
    m = m ? repairTwoStr(m) + "分" : "";
    s = s ? repairTwoStr(s) + "秒" : "";

    return h + m + s;
  }
}

/** 转为秒数 */
export function turnToSeconds(str) {
  let arr = str.split(":");
  return Number(arr[0]) * 3600 + Number(arr[1]) * 60 + Number(arr[2]);
}

// 截取字符长度限制以内的字符
export function getActiveStr(str = "", total = 8) {
  let realLength = 0;
  str = String(str);
  let len = str.length;
  let result = "";
  if (len === 0) {
    return "";
  }
  for (let i = 0; i < len; i++) {
    if (str.charCodeAt(i) > 128) {
      realLength += 2;
    } else {
      realLength += 1;
    }
    if (realLength > total) {
      return result + "...";
    }
    result = result + str.charAt(i);
  }
  return result;
}

/** 获取字符长度 数字中文算2个 */
export function getStrLength(str = "") {
  let realLength = 0;
  str = String(str);

  for (let i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 128) {
      realLength += 2;
    } else {
      realLength += 1;
    }
  }

  return realLength;
}

/** 取随机数 */
export function random(max) {
  return Math.round(Math.random() * max);
}

/** 超时 */
export function delayTimeout(time) {
  return new Promise((resolve, reject) => {
    setTimeout(reject, time);
  });
}

/** 函数防抖 */
export function debounce(fn, wait = 300) {
  var timer = null;

  return function (...args) {
    if (timer !== null) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn(...args);
    }, wait);
  };
}

export const _debounce = function (fn, delay) {
  let timer = null;
  return function (...args) {
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

/** 函数节流 */
export function throttle(fn, wait = 300) {
  let locked = false;

  return function (...args) {
    if (locked) return;
    locked = true;
    setTimeout(() => {
      locked = false;
    }, wait);

    fn(...args);
  };
}

/** 将毫秒  满一分钟则单位分钟   否则单位秒 */
export function formatTime(time) {
  time = Math.floor(time / 1000);
  if (time < 60) return time + "秒";
  return Math.floor(time / 60) + "分钟";
}

/** 匹配手机号 */
export function matchPhoneNumber(str) {
  str = str.replace(/-/g, "");
  const reg = /1[3456789]\d{9}/;
  const result = str.match(reg);

  return result ? result[0] : "";
}

/** 匹配所有的手机号 */
export function matchAllPhoneNumber(str) {
  str = str.replace(/-/g, "");
  const reg = /1[3456789]\d{9}/g;
  let arr;
  if (str.matchAll) {
    arr = [...str.matchAll(reg)];
  } else {
    arr = [...matchAll(str, reg)];
  }

  let result = "";
  arr.forEach((item, i) => {
    if (i == 0 && item.index != 0) {
      result = item.input.slice(0, item.index);
    }
    result =
      result +
      encryptPhoneNumber(item[0]) +
      item.input.slice(item.index + item[0].length, arr[i + 1] && arr[i + 1].index);
  });

  // console.log(arr);

  return result;
}

/** 手机号加密 */
export function encryptPhoneNumber(str) {
  str = String(str);
  return str.slice(0, 3) + "****" + str.slice(7);
}

function add0(m) {
  return m < 10 ? "0" + m : m;
}

export function parseDate(timestamp) {
  var time = new Date(timestamp);
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();

  return y + "-" + add0(m) + "-" + add0(d) + " " + add0(h) + ":" + add0(mm) + ":" + add0(s);
}

var currentTime = new Date();
var currentYear = currentTime.getFullYear();
var currentMonth = currentTime.getMonth() + 1;
var currentDay = currentTime.getDate();

// 年月日格式化
export function dateFormat(timestamp, options = {}) {
  var time = new Date(timestamp);
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  var mm = time.getMinutes();
  var s = time.getSeconds();

  var result = add0(m) + "月" + add0(d) + "日";
  if (currentYear !== y) {
    result = add0(y) + "年" + result;
  }

  if (options.showHourMin) {
    let hm = add0(h) + ":" + add0(mm);
    if (currentYear == y && currentMonth == m && currentDay == d) {
      return hm;
    }
    result += " " + hm;
  }

  return result;
}

// 保留小数点后几位
export function formatDecimal(num, decimal = 2) {
  num = String(num);
  let pointIndex = num.indexOf(".");
  if (pointIndex > -1) {
    return num.slice(0, pointIndex + decimal + 1);
  } else {
    return num;
  }
}

/** 匹配搜索关键词高亮 */
export function mathchSearchValue(str, searchText, normalClass='text-black', specialClass='text-red') {
  let arr;
  if (str.matchAll) {
    arr = [...str.matchAll(new RegExp(searchText, "g"))];
  } else {
    arr = [...matchAll(str, new RegExp(searchText, "g"))];
  }

  let indexList = arr.map((item) => item.index);

  let result = [];
  if (indexList[0] != 0) {
    result.push({ color: normalClass, text: str.slice(0, indexList[0]) });
  }
  indexList.forEach((item, index) => {
    result.push({ color: specialClass, text: searchText });
    result.push({ color: normalClass, text: str.slice(item + searchText.length, indexList[index + 1]) });
  });

  return result;
}

export function matchAll(str, reg) {
  var res = [];
  var match;
  while ((match = reg.exec(str))) {
    res.push(match);
  }
  return res;
}

//转换年月日方法
export function getDate(format, str) {
  var oDate = new Date(str),
    oYear = oDate.getFullYear(),
    oMonth = oDate.getMonth() + 1,
    oDay = oDate.getDate(),
    oHour = oDate.getHours(),
    oMin = oDate.getMinutes(),
    oSec = oDate.getSeconds(),
    oTime;
  console.log(oDate, 666, str);
  if (format == "yyyy-mm-dd") {
    oTime = oYear + "-" + getzf(oMonth) + "-" + getzf(oDay);
  } else if (format == "yyyy/mm/dd") {
    oTime = oYear + "/" + getzf(oMonth) + "/" + getzf(oDay);
  }
  return oTime;
}
//补0操作
export function getzf(num) {
  if (parseInt(num) < 10) {
    num = "0" + num;
  }
  return num;
}

/**复杂数组去重 */
export function uniqueComplex(arr, fn) {
  if (!Array.isArray(arr) || typeof fn !== "function") {
    return [];
  }
  let obj = {};
  arr.forEach((item) => {
    obj[fn(item)] = item;
  });

  return Object.values(obj);
}

/**
 * 接口轮询
 * @param {*} ajax 异步调用接口
 * @param {*} handler 处理接口数据的回调，若返回值 === true 则继续轮询
 * @param {*} time 轮询的间隔时间
 * @param {*} immediat 是否立即执行一次
 * @returns 函数   执行该函数则强制停止轮询
 */
export function pollingModeRequest(ajax, handler, time = 1000, immediate = true) {
  let timer = null;
  let clearTimer = () => {
    timer && clearTimeout(timer);
    timer = null;
  };

  function goon() {
    ajax((res) => {
      let result = handler(res);
      
      clearTimer();
      if (result === true) {
        timer = setTimeout(() => {
          goon()
        }, time);
      }
    });  
  }

  goon();

  return clearTimer;
}

// 手机号校验
export function phoneNumberCheck(number) {
  return /^1[0-9]{10}$/.test(number)
}

// 严格手机号校验
export function phoneNumberStrictCheck(number) {
  return /^1[3456789]\d{9}$/.test(number)
}

export function isWhatType(o) {
  return Object.prototype.toString.call(o).slice(8, -1)
}

// http地址校验
export function httpUrlCheck(url) {
  return /^http/.test(url)
}

// 发房参数校验规则
const _publishParamsRules = {
  area: function(value) {
    return !!value && !!(Number(value) > 0)
  },
  salse: function(value) {
    return !!value && !!(Number(value) > 0)
  },
  rent: function(value) {
    return !!value && !!(Number(value) > 0)
  },
  shi: function(value) {
    return !!value && !!(Number(value) > 0)
  },
  ting: function(value) {
    return !!value && !!(Number(value) >= 0)
  },
  wei: function(value) {
    return !!value && !!(Number(value) >= 0)
  },
}

/**
 * 校验发房必填参数
 * @param {object} volidates 校验集合 key与校验规则名对应
 * @param {*} area 面积
 * @param {*} salse 售价
 * @param {*} rent 租格
 * @param {*} shi 室
 * @param {*} ting 厅
 * @param {*} wei 卫
 */
export const volidatePublishParams = function (volidates) {
  return Object.keys(volidates).every(key => {
    return _publishParamsRules[key](volidates[key])
  })
}
